package com.github.crush0.myblog.controller;

import com.github.crush0.myblog.dao.SortInfoMapper;
import com.github.crush0.myblog.entity.SortInfo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 分类信息控制器
 * @author crush0
 */
@RestController
@RequestMapping("/api/sort")
public class SortController  extends BaseController{
    private SortInfoMapper sortInfoMapper;

    @Autowired
    public SortController(SortInfoMapper sortInfoMapper){
        this.sortInfoMapper = sortInfoMapper;
    }
    /**
     * 获取所有分类信息
     *
     * @return
     */
    @ApiOperation("获取所有分类信息")
    @GetMapping("/list")
    public List<SortInfo> listAllSortInfo() {
        return sortInfoMapper.selectAll();
    }

    /**
     * 通过id获取一条分类信息
     *
     * @param id
     * @return
     */
    @ApiOperation("获取某一条分类信息")
    @ApiImplicitParam(name = "id", value = "分类ID", required = true, dataType = "Long")
    @GetMapping("/{id}")
    public SortInfo getSortInfoById(@PathVariable Long id) {
        return sortInfoMapper.selectByPrimaryKey(id);
    }

    /**
     * 增加一条分类信息数据
     *
     * @return
     */
    @ApiOperation("增加分类信息")
    @ApiImplicitParam(name = "name", value = "分类名称", required = true, dataType = "string")
    @PostMapping("/{name}")
    public String addSortInfo(@PathVariable String name) {
        SortInfo newRecord = new SortInfo();
        newRecord.setName(name);
        newRecord.setCreate_by(new Date());
        newRecord.setModified_by(new Date());
        sortInfoMapper.insert(newRecord);
        return "success";
    }

    /**
     * 更新/编辑一条数据
     *
     * @param id
     * @param name
     * @return
     */
    @ApiOperation("更新/编辑分类信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "分类ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "name", value = "新的分类名称", required = true, dataType = "string")
    })
    @PutMapping("/{id}")
    public String updateSortInfo(@PathVariable Long id,String name) {
        SortInfo record = sortInfoMapper.selectByPrimaryKey(id);
        record.setName(name);
        sortInfoMapper.updateByPrimaryKey(record);
        return "success";
    }

    /**
     * 根据ID删除分类信息
     *
     * @param id
     * @return
     */
    @ApiOperation("删除分类信息")
    @ApiImplicitParam(name = "id", value = "分类ID", required = true, dataType = "Long")
    @DeleteMapping("/{id}")
    public String deleteSortInfo(@PathVariable Long id) {
        sortInfoMapper.deleteByPrimaryKey(id);
        return "success";
    }
}

